//
//  ViewController.swift
//  YSM
//
//  Created by ys on 2018/7/13.
//  Copyright © 2018年 ys. All rights reserved.
//

import UIKit
import Alamofire

class ViewController: BaseViewController {
    
    private var label: UILabel!

    private var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initData()
        self.initView()
        self.registerNotify()
        
        
        initBBJ()
    }
    
    override func reciveRouterCommon(name: Notification.Name, params: Any?) {
        if name == .RLoginSucess {
            print("\(self.classForCoder) 登录成功 回调 \(params ?? "无参数")")
        }else if name == .RLogout {
            print("\(self.classForCoder) 退出登录 回调 \(params ?? "无参数")")
        }
        
        self.label.text = params as? String

    }
    //MARK: - ***** private Method *****
    private func initData() {
        self.navigationItem.title = "一级页面"
    }
    private func initView() {
        self.label = UILabel(frame: CGRect(x: 50, y: 100, width: 200, height: 30))
        self.label.backgroundColor = .lightGray
        self.label.text = "默认显示"
        self.view.addSubview(self.label)
        
        self.button = UIButton(frame: CGRect(x: 50, y: 200, width: 200, height: 30))
        self.button.backgroundColor = .red
        self.button.setTitle("跳转二级页面", for: .normal)
        self.button.addTarget(self, action: #selector(clickNext), for: .touchUpInside)
        self.view.addSubview(self.button)
    }
    
    
    @objc private func clickNext() {
        let vc = YSRouter.loadVC(vcName: "SecondViewController")
        vc.loadVCInfo(params:["title":"二级页面", "id": 1])
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func registerNotify() {
        YSRouterCommon.addRouterCommon(names: .RLoginSucess, target: self)
    }
    
    
    @objc private func loginSuccess(notifi:Notification) {
        print(notifi.name)
        self.label.text = notifi.object as? String
    }


    //private let randomStringArray: [Character] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".map({$0})
    private let randomStringArray: [Character] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".map({$0})

    
    var key:String = "12345678"

}

extension ViewController {
    
    func randomStringOfLength(_ length:Int) -> String {
        var string = ""
        for _ in (1...length) {
            string.append(randomStringArray[Int(arc4random_uniform(
                UInt32(randomStringArray.count) - 1))])
        }
        return string
    }
    
    /// 加密
    func encryptUseDES(encryptString:String, key: String) -> String{
        
        let inputData : Data = encryptString.data(using: String.Encoding.utf8)!
        
        let keyData: Data = key.data(using: String.Encoding.utf8, allowLossyConversion: false)!
        let keyBytes = UnsafeMutableRawPointer(mutating: (keyData as NSData).bytes)
        
        let dataLength = Int(inputData.count)
        let dataBytes = UnsafeRawPointer((inputData as NSData).bytes)
        let bufferData = NSMutableData(length: Int(dataLength) + kCCBlockSize3DES)!
        let bufferPointer = UnsafeMutableRawPointer(bufferData.mutableBytes)
        let bufferLength = size_t(bufferData.length)
        var bytesDecrypted = Int(0)
        
        let cryptStatus = CCCrypt(
            UInt32(kCCEncrypt), UInt32(kCCAlgorithmDES),
            UInt32(kCCOptionPKCS7Padding),
            key, kCCKeySizeDES,
            keyBytes,
            dataBytes, dataLength,
            bufferPointer,
            bufferLength,
            &bytesDecrypted)
        
        if Int32(cryptStatus) == Int32(kCCSuccess) {
            bufferData.length = bytesDecrypted
            
            let plaindata = Data(bytes: bufferPointer, count: bufferData.length)
            
            let clearDataAsString = plaindata.base64EncodedString()
            return clearDataAsString
        }
        return ""
    }
    
    /// 解密
    func decryptUseDES(encryptString : String, key: String) -> String {
        
        let inputData = Data(base64Encoded: encryptString)
        let keyData: Data = key.data(using: String.Encoding.utf8, allowLossyConversion: false)!
        let keyBytes = UnsafeMutableRawPointer(mutating: (keyData as NSData).bytes)
        let dataLength = inputData?.count
        let dataBytes = UnsafeRawPointer((inputData! as NSData).bytes)
        let bufferData = NSMutableData(length: dataLength! + kCCBlockSize3DES)!
        let bufferPointer = UnsafeMutableRawPointer(bufferData.mutableBytes)
        let bufferLength = size_t(bufferData.length)
        var bytesDecrypted = Int(0)
        
        let cryptStatus = CCCrypt(
            UInt32(kCCDecrypt), UInt32(kCCAlgorithmDES),
            UInt32(kCCOptionPKCS7Padding),
            key, kCCKeySizeDES,
            keyBytes,
            dataBytes, dataLength!,
            bufferPointer, bufferLength,
            &bytesDecrypted)
        
        if Int32(cryptStatus) == Int32(kCCSuccess) {
            bufferData.length = bytesDecrypted
            let plaindata = Data(bytes: bufferPointer, count: bufferData.length)

            let clearDataAsString = String(data: plaindata, encoding: String.Encoding.utf8)
            return clearDataAsString ?? ""
//            print("解密后的内容：\(clearDataAsString! as String)")
        }
        
        return ""
    }

}

extension ViewController {
    
    func initBBJ() {
//        Alamofire.request("https://httpbin.org/get", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (res) in
//            print(res.description)
//        }
        
        HTTPTool.get(url: "http://192.168.100.194:8888/index/api/index", httpName: nil) { (result) in
            print("res = \(result.resultStr),\n content = \(String(describing: result.resultContent))")
        }
        
        
        let dic: [String: Any] = [:]
        HTTPTool.get(url: "", header: dic, httpName: "asdfsdf") { (result) in
            
        }
                
//        HTTPTool.reques
//        let request = Alamofire.request("https://httpbin.org/get")
//        Alamofire.req
    }
    
}




